package com.xiewenyu.web.servlets;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取下载文件懂路径
        String realPath=this.getServletContext().getRealPath("/测试.png");
        realPath="E:\\桌面工作目录\\编程代码区\\idea\\mavenJava\\java-web-01\\target\\classes\\测试.png";
        //2 下载文件名是啥
        String fileName=realPath.substring(realPath.lastIndexOf("\\")+1);
        //3 设置浏览器支持Content-Disposition下载的东西
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //4 获取下载文件的输入流
        FileInputStream in=new FileInputStream(realPath);

        //5创建缓冲区
        int len=0;
        byte[] buffer=new byte[1024];

        //6获取输出流对象
        ServletOutputStream out = resp.getOutputStream();

        //7将文件输入流写入到buffer
        while ((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }

        //释放资源
        in.close();
        out.close();
    }
}
